package com.thinkgem.javamg.modules.busi.utils;

import com.thinkgem.javamg.common.utils.StringUtils;
import com.thinkgem.javamg.modules.busi.dto.ProxyInfoDTO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Jsoup操作工具栏
 */
public class JsoupUtil {

    protected static Logger logger = LoggerFactory.getLogger(JsoupUtil.class);

    public static Document getDocument(String url) {
        Document doc = null;
        try {
            doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31").timeout(30 * 1000).get();
        } catch (Exception e) {
            //被封IP出现异常，启用代理IP
            doc = getDocumentByProxy(url);
            logger.error(e.getMessage());
        }
        return doc;
    }

    /**
     * 通过代理方式获取
     *
     * @param url
     * @return
     */
    public static Document getDocumentByProxy(String url) {
        Document doc = null;
        try {
            //得到一个可用的代理ip信息
            ProxyInfoDTO proxyInfoDTO = ProxyUtil.getOne();
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", proxyInfoDTO.getIp());
            System.setProperty("http.proxyPort", proxyInfoDTO.getPort());
            doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31").timeout(30 * 1000).get();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return doc;
    }


    /**
     * 获取第一个元素的文本
     *
     * @return
     */
    public static String getFirstElementText(Elements elements) {
        if (null != elements && elements.size() > 0) {
            return elements.get(0).text();
        }
        return "";
    }


    /**
     * 获取第一个元素的文本(自己的)
     *
     * @return
     */
    public static String getFirstElementOwnText(Elements elements) {
        if (null != elements && elements.size() > 0) {
            return elements.get(0).ownText();
        }
        return "";
    }

    /**
     * 获取第一个元素的属性值
     *
     * @return
     */
    public static String getFirstElementAttrText(Elements elements, String attrKey) {
        if (null != elements && elements.size() > 0) {
            return elements.get(0).attr(attrKey);
        }
        return "";
    }

    /**
     * 获取元素的文本
     *
     * @return
     */
    public static String getElementText(Element element) {
        if (null != element) {
            return element.text();
        }
        return "";
    }

    /**
     * 获取元素属性值
     *
     * @return
     */
    public static String getElementAttrText(Element element, String attrKey) {
        if (null != element) {
            return element.attr(attrKey);
        }
        return "";
    }

    /**
     * 去掉内容第一张图片
     *
     * @param content
     * @return
     */
    public static String removeFirstImg(String content) {
        try {
            Element contentElement = Jsoup.parse(content);
            Elements imgElements = contentElement.getElementsByTag("img");
            if (null != imgElements && imgElements.size() > 0) {
                imgElements.get(0).remove();
                return contentElement.getElementsByTag("body").html();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return content;
    }

    /**
     * 删除指定的某个元素
     *
     * @param element
     */
    public static void removeElement(Element element) {
        if (null != element) {
            element.remove();
        }
    }

    /**
     * 删除指定多个元素
     *
     * @param elements
     */
    public static void removeElements(Elements elements) {
        for (Element element : elements) {
            removeElement(element);
        }
    }

    /**
     * 字符数组转字符串
     *
     * @param arr
     * @return
     */
    public static String arrToString(String[] arr) {
        StringBuilder sb = new StringBuilder("");
        for (String str : arr) {
            sb.append(str).append(" ");
        }
        return sb.toString();
    }

}
